package com.test.springboot.springBootUtils.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.test.springboot.springBootUtils.bean.AbsTask;

@RestController
public class ValidController {
	/**
	 * 使用 BindingResult 处理校验返回的信息
	 * @author huyong
	 * @date 2020年8月25日下午3:58:11
	 * @param absTask
	 * @param bindingResult
	 * @return
	 * @return Object
	 */
	@PostMapping(value = "/createTaskByBindingResult", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Object createTaskByBindingResult(@RequestBody @Valid AbsTask absTask, BindingResult bindingResult) {
		Map<String, Object> map = new HashMap<String, Object>();
		// 先获取校验的参数是否正确
		List<ObjectError> allErrors = bindingResult.getAllErrors();
		if (!CollectionUtils.isEmpty(allErrors)) {
			map.put("date", allErrors.stream().findFirst().get());
		} else {
			map.put("date", "SUCCESS");
		}
		return map;
	}

	/**
	 * 使用抛出异常，和全局 异常处理来校验每个接口数据
	 * @author huyong
	 * @date 2020年8月25日下午3:59:12
	 * @param absTask
	 * @param bindingResult
	 * @return
	 * @return Object
	 */
	@PostMapping(value = "/createTask", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Object createTask(@RequestBody @Valid AbsTask absTask) {
		Map<String, Object> map = new HashMap<String, Object>();
		// 先获取校验的参数是否正确
		map.put("date", "SUCCESS");
		return map;
	}

}
